#include "lib/pipc.hpp"
#include "lib/protocol.hpp"
#include <iostream>
#include <boost/thread.hpp>

using namespace std;
using namespace pipc;

int main(int argc, char** argv)
{
#ifdef READER
    Pipc * reader = Pipc::Instance();
    reader->initialize("pipc.xml", std::string(argv[1]));
    reader->start();

    boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
    reader->subscribe("key0",true);
    while(true)
    {
        Record r;
        r = reader->getValue("key0");
        boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    }
#endif

#ifdef WRITER
    int count = 0;
    Pipc * writer = Pipc::Instance();
    writer->initialize("pipc.xml", std::string(argv[1]));
    writer->start();

    boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
    writer->subscribe("key0",false);
    std::vector <int64_t>  results;
    while(true)
    {
        Record r, old;
        r.data ="value";

        gettimeofday(&r.effective, NULL);
        old = r;


        writer->setValue("key0",r);

        while(!writer->isSynced("key0")){boost::this_thread::sleep(boost::posix_time::milliseconds(1));}

        r = writer->getValue("key0");
        results.push_back(timeval_to_usec(&r.effective) - timeval_to_usec(&old.effective));
        if(count > 300)
        {
            for(int i = 0; i< 300; i++)
                cout << results[i] << endl;
            break;
        }
        else
            count++;
    }
    std::string temp;
    if(argc == 3)
        cin >> temp;
    return 0;
#endif
}

